<?php
namespace App\Services;

use Illuminate\Http\Request;
use App\Models\WxQrcodeGroup;
use App\Models\WxQrcodeUse;
use Illuminate\Support\Facades\Cache;

class WxQrcodeGroupService
{
    /**
     * 构造函数
     */
    public function __construct()
    {

    }

    /**
     * 获取分组列表
     * @param bool $isRefresh
     * @return mixed
     */
    public function getGroupList($isRefresh = false)
    {
        $cacheKey = 'wxqrcodegroup_menulistbygroupkey';
        //Cache::delete($cacheKey);
        $cacheData = Cache::get($cacheKey);
        if (!$cacheData || $isRefresh){
            $groupList = WxQrcodeGroup::all()->toArray();
            $cacheData = [];
            if ($groupList){
                foreach ($groupList as $v){
                    $cacheData[(int) $v['group_id']] = $v;
                }
            }

            Cache::put($cacheKey, $cacheData, 60);
        }
        return $cacheData;
    }

    /**
     * 通过ID获取菜单分组数据
     * @param $groupId
     * @return array
     */
    public function getGroupDataById($groupId)
    {
        $groupList = $this->getGroupList();
        return isset($groupList) ? $groupList[$groupId] : [];
    }
    /**
     * 保存数据
     * @param Request $request
     * @return bool
     */
    public function save(Request $request)
    {
        if ($request->group_id){
            $group = WxQrcodeGroup::find($request->group_id);
        }else{
            $group = new WxQrcodeGroup;
        }
        $group->group_key = $request->group_key;
        $group->group_name = $request->group_name;
        $group->description = $request->description ?? '';
        $group->is_forever = $request->is_forever;
        $rs = $group->save();
        //更新缓存
        $this->getGroupList(true);
        return $rs;

    }

    /**
     * 删除模型
     * @param $groupId
     * @return mixed
     */
    public function del($groupId)
    {
        $group = WxQrcodeGroup::findOrFail($groupId);
        $findQrCode = WxQrcodeUse::where('group_id', $groupId)->first();
        if ($findQrCode){
            throw new \Exception('该分组下还有未删除的二维码，不能删除');
        }
        $rs = $group->delete();
        //更新缓存
        $this->getGroupList(true);
        return $rs;
    }
}